package com.heima.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.vo.UserVo;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 登录接口
     *   二合一，用户登录也是有游客登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {

        String phone = dto.getPhone();
        String password = dto.getPassword();
        if(StrUtil.isBlank(password)||StrUtil.isBlank(phone)){
            String token = AppJwtUtil.getToken(0L);
            return ResponseResult.okResult(token);
        }

        ApUser apuser = this.lambdaQuery()
                .eq(ApUser::getPhone, phone).one();

        if(apuser==null){
            ResponseResult.errorResult(1002,"用户不存在");
        }
        String gensalt = BCrypt.gensalt();
        String hashpw = BCrypt.hashpw(password, gensalt);
        if(!hashpw.equals(apuser.getPassword())){
            ResponseResult.errorResult(2,"用户密码错误");
        }

        String token = AppJwtUtil.getToken(Long.valueOf(apuser.getId()));
        Map<String,Object> map = new HashMap<>();
        UserVo userVo = new UserVo();
        userVo.setId(apuser.getId());
        userVo.setName(apuser.getName());
        userVo.setPhone(apuser.getPhone());
        map.put("user",userVo);
        map.put("token", token);
        return ResponseResult.okResult(map);
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser> findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
